from netCDF4 import Dataset

# file_path指向wrfout文件的路径
file_path = '/Users/caopeihao/Downloads/wrfout_d01_2018-09-23_00_00_00'

try:
    ncfile = Dataset(file_path, 'r')  # 'r' for read mode

    print("NetCDF File Information:")
    print(ncfile)  # Prints a summary of the file structure

    print("\nDimensions:")
    for dim_name in ncfile.dimensions:
        dim = ncfile.dimensions[dim_name]
        print(f"  {dim_name}: size = {dim.size}, unlimited = {dim.isunlimited()}")

    print("\nVariables:")
    for var_name in ncfile.variables:
        var = ncfile.variables[var_name]
        print(f"  {var_name}: shape = {var.shape}, dimensions = {var.dimensions}, dtype = {var.dtype}")
        if var.long_name: # Check if 'long_name' attribute exists
            print(f"    long_name: {var.long_name}")
        if var.units:      # Check if 'units' attribute exists
            print(f"    units: {var.units}")
        # 可以输出 'standard_name', 'valid_range'等属性
        print("    Attributes:", var.ncattrs())
        for attr_name in var.ncattrs():
            print(f"      {attr_name}: {var.getncattr(attr_name)}")


    print("\nGlobal Attributes:")
    for attr_name in ncfile.ncattrs():
        print(f"  {attr_name}: {ncfile.getncattr(attr_name)}")

except FileNotFoundError:
    print(f"Error: NetCDF file not found at '{file_path}'")
except Exception as e:
    print(f"An error occurred: {e}")
finally:
    if 'ncfile' in locals() and ncfile: # Ensure ncfile is defined and not None
        ncfile.close() # Important: Close the file when done